import React, { useContext, memo, useCallback, useMemo, useEffect, useState } from 'react';
import { DatePicker, Form, Dropdown, Button, Menu, Select } from 'antd';
import moment from 'moment';

import { isSuccess } from '@/utils/request';
import OrganizationSelect from '@/components/OrganizationSelect';

import SalaryPageProvider from '@/pages/SalaryManage/components/SalaryPageWrapper/SalaryPageProvider';
import Search from '@/pages/SalaryManage/components/SuperSearch';
import TwoColHead from '@/pages/SalaryManage/components/TwoColHead';
import useCheckButton from '@/pages/SalaryManage/SalaryCalculate/Recheck/components/CheckHandle/useCheckButton';
import If from '@/components/If';
import BizIcon from '@/components/BizIcon';
import AutoDivider from '@/pages/SalaryManage/components/AutoDivider';
import { goToProcessDetail } from '@/pages/SalaryManage/utils/pageNavigateUtil';

import { queryDictList, salaryRecheck } from '@/services/salaryManage/salaryCalculate';

import { download } from '@/utils/utils';

import { BUTTON } from '@/pages/SalaryManage/SalaryCalculate/constant/recheckButtonConstant';

import BaseMore from './baseMore';
import styles from './index.less';

const { excelExport } = salaryRecheck;
const { MonthPicker } = DatePicker;

//  搜索栏
const SearchWrapper = memo(({ form, checkButtonList, headerList, nodeCode }) => {
    const salaryProvider = useContext(SalaryPageProvider);
    const { period, organizationCode, searchModel, organizationTreeData, changeSalaryProviderParam } = salaryProvider;

    const { getFieldDecorator } = form;

    const { render: buttonRender } = useCheckButton(checkButtonList);

    const [distMap, setDictMap] = useState({
        financeCheckStatusEnum: [],
        hrCheckStatusEnum: []
    });

    useEffect(() => {
        const getDictList = async () => {
            const dictRes = await queryDictList('financeCheckStatusEnum,hrCheckStatusEnum');
            if (isSuccess(dictRes)) {
                setDictMap({
                    ...dictRes.data
                });
            } else {
                setDictMap({
                    financeCheckStatusEnum: [],
                    hrCheckStatusEnum: []
                });
            }
        };
        setTimeout(() => {
            getDictList();
        });
    }, []);

    //  月份切换事件
    const onChange = (date, dateString) => {
        changeSalaryProviderParam({
            period: dateString
        });
    };

    const { departmentCode } = searchModel;

    // 1.设置默认选择月份
    const periodMoment = period ? moment(period) : null;

    const handleOrgChange = val => {
        changeSalaryProviderParam({
            type: 'changeOrg',
            organizationCode: val
        });
    };

    const handleDepChange = val => {
        changeSalaryProviderParam({
            type: 'initPage',
            searchModel: {
                ...searchModel,
                departmentCode: val
            }
        });
    };

    const getRightButton = useCallback(code => (checkButtonList || []).find(item => item.code === code), [
        checkButtonList
    ]);

    // 是否需要显示按钮
    const needShowButton = useCallback(
        code => {
            const matchButton = getRightButton(code);
            return matchButton && !matchButton.disabled;
        },
        [getRightButton]
    );

    const excelExportFn = useCallback(async () => {
        const year = period.substr(0, 4);
        const month = period.substr(5);
        download({
            getData: () =>
                excelExport({
                    year,
                    month,
                    organizationCode,
                    nodeCode,
                    tableHeaderItemList: headerList,
                    page: {
                        pageNo: 1,
                        pageSize: 10
                    },
                    ...searchModel
                })
        });
    }, [headerList, nodeCode, organizationCode, period, searchModel]);

    const dropDownMenu = useMemo(() => {
        const dropMenu = [];

        if (needShowButton(BUTTON.EXCEL_EXPORT) || needShowButton(BUTTON.FN_EXCEL_EXPORT)) {
            dropMenu.push(
                <Menu.Item key={BUTTON.EXCEL_EXPORT} onClick={excelExportFn}>
                    Excel导出
                </Menu.Item>
            );
        }

        return dropMenu;
    }, [excelExportFn, needShowButton]);

    const goToSubmitDetail = () => {
        const submitButton = getRightButton(BUTTON.FN_SUBMIT_DETAIL);
        goToProcessDetail(submitButton.butQueryParamVO);
    };

    const searchHandle = () => {
        const { hireDate, ...searchValue } = form.getFieldsValue();
        changeSalaryProviderParam({
            type: 'initPage',
            searchModel: {
                ...searchModel,
                ...searchValue,
                hireDate,
                hireDateBegin: hireDate?.[0] ? hireDate[0].format('YYYY-MM-DD') : null,
                hireDateEnd: hireDate?.[1] ? hireDate[1].format('YYYY-MM-DD') : null
            }
        });
    };

    return (
        <Search.Wrapper style={{ marginTop: 20 }} onSearch={searchHandle}>
            <TwoColHead
                rightStyle={{ justifyContent: 'flex-start' }}
                left={
                    <Search.Commonly>
                        <Search.Item label="机构">
                            <OrganizationSelect
                                isStrictly
                                allowClear={false}
                                isNeedPermission
                                style={{ width: 220 }}
                                value={organizationCode}
                                treeDataFromProp
                                treeDataList={organizationTreeData}
                                onChange={handleOrgChange}
                                unLoading
                            />
                        </Search.Item>
                        <Search.Item>
                            <OrganizationSelect
                                isStrictly
                                isFunctional
                                style={{ width: 150 }}
                                value={departmentCode}
                                onChange={handleDepChange}
                                extraQuery={{ auditStatus: 2 }}
                                unLoading
                            />
                        </Search.Item>
                        <Search.Item label="月份">
                            <MonthPicker
                                onChange={onChange}
                                value={periodMoment}
                                style={{ width: '110px' }}
                                allowClear={false}
                            />
                        </Search.Item>
                    </Search.Commonly>
                }
                right={
                    <TwoColHead
                        style={{ margin: 0, width: '100%' }}
                        left={buttonRender()}
                        right={
                            <AutoDivider>
                                <If condition={needShowButton(BUTTON.FN_SUBMIT_DETAIL)}>
                                    <Button type="link" onClick={goToSubmitDetail} style={{ padding: 0 }}>
                                        查看审批详情
                                    </Button>
                                </If>

                                <If condition={dropDownMenu.length > 0}>
                                    <Dropdown overlay={<Menu>{dropDownMenu}</Menu>} placement="bottomRight">
                                        <BizIcon type="listfunction_more_icon_default" className={styles.font22} />
                                    </Dropdown>
                                </If>
                            </AutoDivider>
                        }
                        addMarginInRightChild={false}
                    />
                }
            />
            <BaseMore form={form} searchModel={searchModel} organizationCode={organizationCode}>
                <Search.Item label="HR复核状态">
                    {getFieldDecorator('hrCheckStatus', {
                        initialValue: ''
                    })(
                        <Select>
                            <Select.Option value="">全部</Select.Option>
                            {distMap?.hrCheckStatusEnum.map(item => (
                                <Select.Option value={item.key} key={item.key}>
                                    {item.value}
                                </Select.Option>
                            ))}
                        </Select>
                    )}
                </Search.Item>
                <Search.Item label="财务复核状态">
                    {getFieldDecorator('financeCheckStatus', {
                        initialValue: ''
                    })(
                        <Select>
                            <Select.Option value="">全部</Select.Option>
                            {distMap?.financeCheckStatusEnum.map(item => (
                                <Select.Option value={item.key} key={item.key}>
                                    {item.value}
                                </Select.Option>
                            ))}
                        </Select>
                    )}
                </Search.Item>
            </BaseMore>
        </Search.Wrapper>
    );
});

export default memo(Form.create()(SearchWrapper));
